import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:rainflutter/model/cart.dart';
import 'package:rainflutter/pages/controller/page/provide/cart_item.dart';

class ProviderChangeTest extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('状态管理')),
        body: Center(
          child: ChangeNotifierProvider<CartModel>(
            create: (_) => CartModel(),
            child: 
            Builder(builder: (context) {
              return Column(
                children: <Widget>[
                  Consumer<CartModel>(
                    builder: (BuildContext context, cart) =>
                        Text("总价: ${cart.totalPrice}"),
                  ),
                  // Builder(builder: (context) {
                    // print("RaisedButton build");
                    // return 
                    TextButton(
                      child: Text("添加商品"),
                      onPressed: () {
                        // listen 设为false，不建立依赖关系
                        print('添加商品');
                        Provider.of<CartModel>(context, listen: false)
                            .add(Item(20.0, 1));
                      },
                    )
                  // })
                ],
              );
            }),
          ),
        ));
  }
}

// 这是一个便捷类，会获得当前context和指定数据类型的Provider
class Consumer<T> extends StatelessWidget {
  Consumer({
    Key key,
    @required this.builder,
    this.child,
  })  : assert(builder != null),
        super(key: key);

  final Widget child;

  final Widget Function(BuildContext context, T value) builder;

  @override
  Widget build(BuildContext context) {
    return builder(
      context,
      Provider.of<T>(context), //自动获取Model
    );
  }
}
